'''
Created on Mar 10, 2010

@author: oabalbin
'''


import os
import sys
import glob
import shutil
import numpy as np
import operator
from optparse import OptionParser
from datetime import datetime
from collections import deque

# My libraries
import signatures.parsers.read_drugbank_db as dgb

import signatures.parsers.read_microarray_data as pm
import signatures.parsers.read_gene_lists as gpm
import signatures.db.tables as dt
import signatures.db.query as dq
'''
import signatures.common.classes as cm #record, arrayMatrix
import signatures.preprocess.tools as tl #filter_constant_genes, get_variable_genes, 
import signatures.seedgenes.seedlist as sd #get_seed_genes, write_varin_file
import signatures.bfrm.paramfile as bp
import signatures.bfrm.bfrm_run as br
import signatures.bfrm.output_parser as bo
import signatures.plotting.plots as myplt
'''


class pipeline():
    
    def __init__(self, dbhost, dbuser, dbpasswd, database):
        
        self.mt = dt.tables(dbhost, dbuser, dbpasswd, database)
        self.mq = dq.query(dbhost, dbuser, dbpasswd, database)
        self.dgb = dgb.drugBankparser(dbhost, dbuser, dbpasswd, database)
        
        
    def write_drugBank_targets(self,outfile, drugDict):
        """
        It writes an output summary of the genes and the possible drugs than target them.
        """
        header = ['targetGen', 'targetProt', 'dbcard', 'genericname', 'brandname', 'casRegistry']
        outfile.write(",".join(header).replace(',','\t')+'\n')
        for g,druglist in drugDict.iteritems():
            for genrecord in druglist:
                outline =[genrecord.targetGen, genrecord.targetProt, genrecord.dbcard, genrecord.genericname, genrecord.brandname, genrecord.casRegistry]
                print outline
                outfile.write(",".join(outline).replace(',','\t')+'\n')
                
    def parse_input_annotfiles(self, annotInputFile):
    
        expr_file, seed_file, outdirs, db_file, samples, factors, typefile={},{},{},{},{},{},'nofile'
    
        for line in annotInputFile:
            fields = line.strip('\n')
                 
            if fields[0][0] == '' or fields[0][0] == '#':
                continue
            
            if fields[0][0] == '@':
                typefile = fields
                continue
            
            fields = fields.split('=')
            dict = {'@Array expression':expr_file, '@Seed genes':seed_file,'@Database file':db_file,'@Samples':samples,'@Output Directories':outdirs,\
                    '@Factors':factors}[typefile]
            if typefile=='@Factors':
                dict[fields[0]] = map(int,fields[1].split(','))
            else:
                dict[fields[0]] = fields[1]
            
            
        return expr_file, seed_file, db_file, samples,  outdirs, factors
    
    
    def drugBank_main(self,genelist, outfolder):
        
        drugDict = self.dgb.get_drungBank_targets(list(set(genelist)))
        self.write_drugBank_targets(outfolder, drugDict)



if __name__ == '__main__':
    
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-f", "--annotFile", dest="annotFile",
                            help="annotation file for all files to use")
    optionparser.add_option("-d", action="store_true", dest="dbtrue",
                            help="create a database. Bool")


    (options, args) = optionparser.parse_args()
       
    # start the pipeline. 
    # read input parameters
    pipe = pipeline("localhost", "oabalbin", "oscar", "signatures")
    
    expr_folder, seed_file, db_file, samples, outdirs, thisfactors = pipe.parse_input_annotfiles(open(options.annotFile))

    #exp_files = pipe.read_files_folder(expr_folder['expdir'],'.txt')
    
    #########
    # create files
    myfilename='drugcards.txt'
    inputfile = expr_folder['expdir'] + myfilename
    outdbfile  = inputfile.replace('.txt','.db')
    outfolder =  outdirs['outdir']
    outtargets_file = outfolder+'drugsBank_targets.txt'
    ########
    
    tp = pm.parser()
    pipe.mt.create_connector()
    gtp = gpm.geneparser()
    
    if options.dbtrue:
        pipe.dgb.parse_drugBankdb(open(inputfile), open(outdbfile,'w'))
        pipe.dgb.create_drugBank_db(expr_folder['expdir'])
        
    # This gene list is a list of genes in each factor.
    factorlist, allgenes = gtp.list_of_nameload_in_factor(open(seed_file['univfile']),thisfactors['usefactors'])    
    for ft in factorlist:
    
        outfile = outdirs['outdir']+'mat_drugBankfactor_'+str(ft.facnum)+'.txt'
        genespair = sorted(ft.genedic.items(), key=operator.itemgetter(1), reverse=True)
        genelist = deque([ gp[0] for gp in genespair])

        drugDict = pipe.dgb.get_drungBank_targets(list(set(genelist)))
        pipe.write_drugBank_targets(open(outfile,'w'), drugDict)
    
    

    






'''
inputfile=open("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/drugcards.txt")
outputfile=open("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/drugcards.db",'w')
tp = pm.parser()
db = drugBankparser("localhost", "oabalbin", "oscar", "signatures")
#db.parse_drugBankdb(inputfile, outputfile)
#db.create_drugBank_db("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/")
#genelist=['ERG','PRKDC','PARP1','DDX5','AR','NUMA1','PRPF8','TOP2B','XRCC5','ABL1','ACP5','ACTL6A']
genelist=tp.list_of_names(open("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/factor_genesTest.txt"))
outfile = open("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/factor_drugTargets.txt",'w')
print genelist
drugDict = db.get_drungBank_targets(list(set(genelist)))

outfile=open("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/drugs_targets.txt",'w')

for g,druglist in drugDict.iteritems():
    for genrecord in druglist:
        outline =[genrecord.targetGen, genrecord.targetProt, genrecord.dbcard, genrecord.genericname, genrecord.brandname, genrecord.casRegistry]
        print outline
        outfile.write(",".join(outline).replace(',','\t')+'\n')
'''